<?php

namespace app\api\controller;

use app\admin\model\weixin\Weixin;
use app\common\controller\Api;

use addons\weixin\library\WechatTemplateService;

/**
 * 认为接口
 */
class Task extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test','getTask','getForTask','task','createTask','getTaskBat','test3','createTaskUnusual'];

    //创建任务表
    public function createTask(){
        $data["wxid"] =  $this->request->post('wxid');
        $data["wxtempid"] =  $this->request->post('wxtempid');
        $data["inform"] =  $this->request->post('inform');
        $data["mobile"] =  $this->request->post('mobile');
        $data["url"] =  $this->request->post('url');
        file_put_contents("createTask.json",var_export($data,true).date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);

        if(empty($data["wxid"])){
            $this->error("公众号参数不能为空");
        }
        if(empty($data["wxtempid"])){
            $this->error("推送模板ID不能为空");
        }

        if(empty($data["inform"])){
            $this->error("推送数据不能为空");
        }

        //处理json
        $json = htmlspecialchars_decode($data["inform"]);
        $jsonarr = json_decode($json,true);

        if(is_null($jsonarr)){
            $this->error("推送数据json不合法");
        }

        if(empty($data["mobile"])){
            $this->error("手机号不能为空");
        }


        //根据手机去查询 openid
        $info = db("user")->field("id,wx_id,openid,nickname")->where(["mobile"=>$data["mobile"],'wx_id'=>$data["wxid"]])->find();
        if($info){
            //写入任务表
            $taskdata["wxid"] = $data["wxid"];
            $taskdata["wxtempid"] = $data["wxtempid"];
            $taskdata["inform"] = $data["inform"];
            $taskdata["url"] = $data["url"];
            $taskdata["useropenid"] = $info["openid"];
            $taskdata["createtime"] = time();

            if(db("task")->insertGetId($taskdata)){
                $this->success("创建任务成功",$taskdata);
            }

        }else{
            $this->error("找不到数据，请核实手机号和微信公众号信息");
        }


    }

    //创建任务表 固定模板 异常提醒
    public function createTaskUnusual(){
        $data["wxid"] =  $this->request->post('wxid');
        $data["mobile"] =  $this->request->post('mobile');
        $data["first"] =  $this->request->post('first');
        $data["keyword1"] =  $this->request->post('keyword1');
        $data["keyword2"] =  $this->request->post('keyword2');
        $data["remark"] =  $this->request->post('remark');
        $data["url"] =  $this->request->post('url');
        file_put_contents("createTask.json",var_export($data,true).date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);

        if(empty($data["wxid"])){
            $this->error("公众号参数不能为空");
        }

        if(empty($data["mobile"])){
            $this->error("手机号不能为空");
        }

        if(empty($data["first"])){
            $this->error("first参数不能为空");
        }

        if(empty($data["keyword1"])){
            $this->error("异常类型不能为空");
        }

        if(empty($data["keyword2"])){
            $data["keyword2"] = date("Y-m-d H:i:s",time());
        }

        if(empty($data["remark"])){
            $this->error("备注不能为空");
        }

        //根据手机去查询 openid
        $info = db("user")->field("id,wx_id,openid,nickname")->where(["mobile"=>$data["mobile"],'wx_id'=>$data["wxid"]])->find();
        if($info){
            //写入任务表
            $taskdata["wxid"] = $data["wxid"];
            unset($data["wxid"]);
            unset($data["mobile"]);
            $taskdata["inform"] = json_encode($data);
            $taskdata["url"] = $data["url"];
            $taskdata["useropenid"] = $info["openid"];
            $taskdata["createtime"] = time();
            $taskdata["wxtempid"] = "eXB3fhFuWJ_mNZhcAvXwScRdC1yikVFIO9pRgAXu8Qs";//异常提醒模板

            if(db("task")->insertGetId($taskdata)){
                $this->success("创建任务成功",$taskdata);
            }

        }else{
            $this->error("找不到数据，请核实手机号和微信公众号信息");
        }


    }



    //获取任务  动态模板

    public function getTaskAuto(){

        $ids =  $this->request->post('data');
        file_put_contents("inform.json",var_export($ids,true).date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
        $task = model("task");
        $info = $task->where("tid={$ids}")->find()->toArray();

        //准备发送数据 发送数据 在 创建任务记录时 准备， 减少推送计算时消耗性能
        //日志数据
        $tid = $info["tid"];
        $edisendtime = $info["sendtime"];
        //推送数据
        $wxid = $info["wxid"];
        $json = htmlspecialchars_decode($info["inform"]);
        $message = json_decode($json,true);
        //$message = json_decode($info["inform"],true);
        $openid = $info["useropenid"];
        $temid = $info["wxtempid"];
        $url = $info["url"];
        $this->task($wxid,$message,$openid,$temid,$url,$tid,$edisendtime);
    }


    //获取任务 固定模板 定时任务

    public function getForTask(){
 
        $list = db("task")->where(["sendflag"=>'N',"sendsucflag"=>0])->select();
        
        if($list){
            

            foreach ($list as $v){

                //日志数据
                $tid = $v["tid"];
                 
                $edisendtime = $v["sendtime"];
              
                //推送数据
                $wxid = $v["wxid"];
                 
                $json = htmlspecialchars_decode($v["inform"]);
                
                
                $message = json_decode($json,true);
                
                $openid = $v["useropenid"];
                
                $temid = $v["wxtempid"];
                 
                $url = $v["url"];
              
                $res = $this->task($wxid,$message,$openid,$temid,$url,$tid,$edisendtime);
                
          
                

            }
        }else{
            echo "die";die;
        }
    }

    //获取任务 固定模板

    public function getTask(){

        $ids =  $this->request->post('data');
        file_put_contents("inform.json",var_export($ids,true).date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
        $task = model("task");
        $info = $task->where("tid={$ids}")->find()->toArray();

        //准备发送数据 发送数据 在 创建任务记录时 准备， 减少推送计算时消耗性能
        //日志数据
        $tid = $info["tid"];
        $edisendtime = $info["sendtime"];
        //推送数据
        $wxid = $info["wxid"];
        $json = htmlspecialchars_decode($info["inform"]);
        $message = json_decode($json,true);
        //$message = json_decode($info["inform"],true);
        $openid = $info["useropenid"];
        $temid = $info["wxtempid"];
        $url = $info["url"];
        $this->task($wxid,$message,$openid,$temid,$url,$tid,$edisendtime);
    }




    //获取任务WIN bat 版定时任务
    public function getTaskBat(){
        //查询未读取的数据
        $task = db("task");
        $list = $task->where("sendflag = 'N'")->field("tid,wxid,sendflag,sendtime,wxtempid,inform,useropenid,url")->select();
        //测试阶段写入日志，方便分析 上线后 可以注释
        file_put_contents("inform.json",var_export($list,true).date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
        if($list){
            //准备发送数据 发送数据 在 创建任务记录时 准备， 减少推送计算时消耗性能
            foreach ($list as $v){
                //日志数据
                $tid = $v["tid"];
                $edisendtime = $v["sendtime"];
                //推送数据
                $wxid = $v["wxid"];
                $json = htmlspecialchars_decode($v["inform"]);
                $message = json_decode($json,true);
                $openid = $v["useropenid"];
                $temid = $v["wxtempid"];
                $url = $v["url"];
                $this->task($wxid,$message,$openid,$temid,$url,$tid,$edisendtime);
            }
        }


    }



    //处理任务
    public function task($wxid,$message,$openid,$temid,$url,$tid,$edisendtime)
    {

        try {
            //进行推送
            $res = WechatTemplateService::sendTemplate($wxid,$openid,$temid,$message,$url); 
            
            if(is_string($res)){
                  $tsk["sendsucflag"] = 1;
                  db("task")->where(["tid"=>$tid])->update($tsk);
            }else{
               
                $tsk["sendsucflag"] = 0;
                 //写入推送记录表
                 $insertData = [];
               if($res && $res["errcode"]==0 && $res["errmsg"] == "ok"){
               
                    $data["task_status"] = 0;
                    //推送成功修改记录
                    $this->updateStatus($tid);
                }else{
                    $data["task_status"] = 1;
                }
     
        
                $insertData["task_time"] = time(); //任务时间 任务表记录
                $insertData["createtime"] = time();
                $insertData["tid"] = $tid;
                $insertData["task_url"] = $url;
                $insertData["task_openid"] = $openid;
                $insertData["task_wxid"] = $wxid;
                $insertData["task_wxtempid"] = $temid;
                $insertData["task_content"] = json_encode($message);
        
                $res2 = $model = model("tasklog");

            }
         
 
         
       
        } catch(Exception $e){
            
            
        }


 

       
        
 
       

    }

    public function updateStatus($id){
        $task = model("task");
        $task->where("tid={$id}")->update(["sendflag"=>'Y',"sendtime"=>time(),"sendsucflag"=>0]);
    }


    public function test3(){

        file_put_contents("test3.json",var_export("11111",true).date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
    }

    public function test(){

        $name = "'{u\'transaction\': None, u\'ts_ms\': 1603272249936, u\'after\': {u\'edisendflag\': u\'Y\', u\'url\': u\'http://www.baidu.com\', u\'useropenid\': u\'oZgEx1JcQ-PLFJFUGnOky5yGdBgA\', u\'inform\': u\'{&quot;first&quot;:&quot;\\\\u4eb2,\\\\u60a8\\\\u7684\\\\u4e1a\\\\u52a1\\\\u72b6\\\\u6001\\\\u53d8\\\\u66f4\\\\u4e86\\\\uff0c\\\\u8fd9\\\\u91cc\\\\u901a\\\\u77e5\\\\u60a8&quot;,&quot;keyword1&quot;:&quot;012345678&quot;,&quot;keyword2&quot;:&quot;100&quot;,&quot;keyword3&quot;:&quot;2020-10-19 04:04:57&quot;,&quot;remark&quot;:&quot;\\\\u70b9\\\\u51fb\\\\u67e5\\\\u770b\\\\u8ba2\\\\u5355\\\\u8be6\\\\u60c5&quot;}\', u\'wxtempid\': u\'jDzwd_lu3eynvfkrc-zjSs8N8mHuZsQZvAGBGwHXwAY\', u\'tid\': 82, u\'wxid\': 19, u\'createtime\': 1603051497, u\'edisendtime\': 1603051497}, u\'source\': {u\'server_id\': 1, u\'name\': u\'VM_0_4_centos\', u\'thread\': 3844, u\'ts_ms\': 1603272249000, u\'db\': u\'wxad\', u\'pos\': 485960, u\'connector\': u\'mysql\', u\'version\': u\'1.2.2.Final\', u\'snapshot\': u\'false\', u\'file\': u\'mysql-bin.000027\', u\'query\': None, u\'table\': u\'fa_task\', u\'gtid\': None, u\'row\': 0}, u\'before\': None, u\'op\': u\'c\'}'";

        $res = unicode_decode($name);

        print_r($res);die;


        echo 2;die;



        die;

        print_r($_SERVER['SERVER_NAME']);die;

        $info = \app\admin\model\weixin\Reply::where("id=8")->find()->toArray();

        $json = json_decode($info["data"],true);


        print_r($json);die;




        die;
        $info = \app\admin\model\weixin\template\Wechat::where("id=5")->find()->toArray();
        $message = array(
            'first' => '亲,您的业务状态变更了，这里通知您',
            'keyword1' => '012345678',
            'keyword2' => '100',
            'keyword3' => date('Y-m-d H:i:s', time()),
            'remark' => '点击查看订单详情'
        );


        $data["wxid"] = 19;
        $data["edisendflag"] = 'N';
        $data["edisendtime"] = time();
        $data["wxtempid"] = $info["tempid"];
        $data["useropenid"] = 'oZgEx1JcQ-PLFJFUGnOky5yGdBgA';
        $data["createtime"] = time();
        $data["inform"] = json_encode($message);

        $task = model("task");

        $inid = $task->insert($data);



        print_r($inid);die;


    }

    //处理任务
    public function task2()
    {

        $message = array(
            'first' => '亲,您的业务状态变更了，这里通知您',
            'keyword1' => '012345678',
            'keyword2' => '100',
            'keyword3' => date('Y-m-d H:i:s', time()),
            'remark' => '点击查看订单详情'
        );

        $res = WechatTemplateService::sendTemplate(
            'oZgEx1JcQ-PLFJFUGnOky5yGdBgA',
            'fsllwarning2',
            $message,
            'http://fastadmin.westts.cn'
        );
        //写入推送记录表
        $data = [];
        if($res && $res["errcode"]==0 && $res["errmsg"] == "ok"){
            $data["task_status"] = 0;
        }else{
           $data["task_status"] = 1;
        }

        $data["task_time"] = time();
        $data["createtime"] = time();
        $data["tid"] = 100;
        $data["task_url"] = "wxad.lvfree.net";
        $data["task_openid"] = "oZgEx1JcQ-PLFJFUGnOky5yGdBgA";
        $data["task_wxid"] = 19;
        $data["task_wxtempid"] = "wfsXxigLlRgI48JgH3boB9FELvoAXSkwlSlbcFw";
        $data["task_content"] = json_encode($message);

        $model = model("tasklog");
        $model->insert($data);



    }


}
